<!DOCTYPE html>
<html lang="">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Demo</title>
    <link href="lib/css/layui.css" rel="stylesheet">
    <style>
        .card {
            margin: 36px auto;
            width: 80%;
            box-shadow: 0 0 6px 2px rgb(222, 222, 222);
            padding: 20px;
            border-radius: 2px;
        }

        .hidden {
            position: absolute;
            left: -100%;
            top: -100%;
        }

        #toolbar-form {
            margin-left: 10px;
            display: inline;
            vertical-align: middle;
        }

        #toolbar-form input[name=keyword] {
            display: inline;
            max-width: 200px;
            height: 30px;
            line-height: 30px;
        }
    </style>
</head>

<body>
    <div class="card">
        <table id="data-table" lay-filter="data-table" class="layui-hide"></table>
    </div>
    <div id="dialog" class="hidden">
        <form id="form" class="layui-form layui-form-pane" style="margin: 16px;">
            <div class="layui-form-item layui-hide">
                <label class="layui-form-label">主键</label>
                <div class="layui-input-block">
                    <input id="id" name="id" type="text" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">用户名</label>
                <div class="layui-input-block">
                    <input id="name" name="name" type="text" autocomplete="off" placeholder="请输入" lay-verify="required"
                        class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">邮箱</label>
                <div class="layui-input-block">
                    <input id="email" name="email" type="text" autocomplete="off" placeholder="请输入"
                        lay-verify="required|email" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">年龄</label>
                <div class="layui-input-block">
                    <input id="age" name="age" type="number" autocomplete="off" placeholder="请输入" lay-verify="required"
                        class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">密码</label>
                <div class="layui-input-block">
                    <input id="password" name="password" type="password" autocomplete="off" placeholder="请输入"
                        lay-verify="required" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item" pane>
                <label class="layui-form-label">管理员</label>
                <div class="layui-input-block">
                    <input id="isAdmin_true" name="isAdmin" type="radio" value="true" title="是">
                    <input id="isAdmin_false" name="isAdmin" type="radio" value="false" title="否" checked>
                </div>
            </div>
            <div class="layui-form-item" style="float: right;">
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                <button class="layui-btn" lay-submit>确认</button>
            </div>
        </form>
    </div>
    <script src="lib/layui.js"></script>
    <script type="text/html" id="toolbar">
        <div class="toolbar">
            <button class="layui-btn layui-btn-sm" lay-event="create">添加</button>
            <form id="toolbar-form">
                <input name="keyword" type="text" autocomplete="off" class="layui-input">
            </form>
        </div>
    </script>
    <script type="text/html" id="rowBar">
        <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="edit">编辑</a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="remove">删除</a>
    </script>
    <script>
        layui.use(['element', 'form', 'table'], function () {
            var $ = layui.$;
            var table = layui.table;
            var layer = layui.layer;
            // 渲染表格
            var tableId = 'table_id_1';
            function searchCondition() {
                var dom = document.querySelector('#toolbar-form input[name=keyword]');
                if (dom && dom.value) {
                    return {
                        sort: 'id desc',
                        search: 'name like :param1',
                        param1: dom.value
                    }
                } else {
                    return {
                        sort: 'id desc'
                    }
                }
            }
            table.render({
                id: tableId,
                elem: '#data-table',
                toolbar: '#toolbar',
                url: '/api/users',
                method: 'get',
                contentType: 'application/x-www-form-urlencoded',
                page: true,
                request: {
                    pageName: 'page',
                    limitName: 'size'
                },
                where: searchCondition(),
                parseData: function (resp) {
                    return {
                        code: resp.code == 200 ? 0 : 1,
                        msg: resp.message,
                        count: resp.data.total,
                        data: resp.data.data
                    };
                },
                defaultToolbar: ['filter', 'exports', 'print'],
                title: '用户数据表',
                cols: [
                    [{
                        type: 'checkbox',
                        fixed: 'left'
                    }, {
                        field: 'id',
                        title: '主键',
                        width: 160
                    }, {
                        field: 'name',
                        title: '用户名',
                        width: 160
                    }, {
                        field: 'email',
                        title: '邮箱',
                        width: 160
                    }, {
                        field: 'age',
                        title: '年龄',
                        width: 160
                    }, {
                        field: 'password',
                        title: '密码',
                        width: 160
                    }, {
                        field: 'isAdmin',
                        title: '是否为管理员',
                        width: 160
                    }, {
                        fixed: 'right',
                        title: '操作',
                        toolbar: '#rowBar',
                        width: 120
                    }]
                ],
            });
            document.querySelector('#toolbar-form').addEventListener('submit', function (event) {
                event.preventDefault();
                table.reloadData(tableId, { where: searchCondition() });
            });
            // 弹出层
            var dialogType = null;
            var dialogIndex = null;
            document.querySelector('#form').addEventListener('submit', function (event) {
                event.preventDefault();
                if (dialogType == 'create') {
                    $.ajax({
                        url: '/api/users',
                        type: 'POST',
                        data: JSON.stringify({
                            name: document.querySelector('#name').value,
                            email: document.querySelector('#email').value,
                            age: document.querySelector('#age').value,
                            password: document.querySelector('#password').value,
                            isAdmin: document.querySelector('#isAdmin_true').checked
                        }),
                        contentType: 'application/json',
                        dataType: 'json',
                        success: function (resp) {
                            if (resp && resp.code == 200) {
                                layer.close(dialogIndex);
                                table.reloadData(tableId, { where: searchCondition() });
                            } else {
                                layer.msg('操作失败', { icon: 2, time: 1200 })
                            }
                        },
                        error: function (xhr, status, error) {
                            console.error(error);
                        }
                    });
                } else if (dialogType == 'edit') {
                    $.ajax({
                        url: '/api/users/' + document.querySelector('#id').value,
                        type: 'PUT',
                        data: JSON.stringify({
                            name: document.querySelector('#name').value,
                            email: document.querySelector('#email').value,
                            age: document.querySelector('#age').value,
                            password: document.querySelector('#password').value,
                            isAdmin: document.querySelector('#isAdmin_true').checked
                        }),
                        contentType: 'application/json',
                        dataType: 'json',
                        success: function (resp) {
                            if (resp && resp.code == 200) {
                                layer.close(dialogIndex);
                                table.reloadData(tableId, { where: searchCondition() });
                            } else {
                                layer.msg('操作失败', { icon: 2, time: 1200 })
                            }
                        },
                        error: function (xhr, status, error) {
                            console.error(error);
                        }
                    });
                }
            });
            table.on('toolbar(data-table)', function (obj) {
                var checkStatus = table.checkStatus(obj.config.id);
                if (obj.event == 'create') {
                    document.querySelector('#id').value = '';
                    document.querySelector('#name').value = '';
                    document.querySelector('#email').value = '';
                    document.querySelector('#age').value = '';
                    document.querySelector('#password').value = '';
                    document.querySelector('#isAdmin_true').checked = false;
                    document.querySelector('#isAdmin_false').checked = true;
                    dialogType = 'create';
                    dialogIndex = layer.open({
                        type: 1,
                        title: '添加',
                        area: ['520px', 'auto'],
                        content: $('#dialog form'),
                    });
                }
            });
            table.on('tool(data-table)', function (obj) {
                var data = obj.data;
                if (obj.event == 'remove') {
                    layer.confirm('确定要删除用户 ' + data.name + ' 吗?', { icon: 0, title: '提示' }, function (index) {
                        $.ajax({
                            url: '/api/users/' + data.id,
                            type: 'DELETE',
                            dataType: 'json',
                            success: function (resp) {
                                if (resp && resp.code == 200) {
                                    table.reloadData(tableId, { where: searchCondition() });
                                } else {
                                    layer.msg('操作失败', { icon: 2, time: 1200 })
                                }
                            },
                            error: function (xhr, status, error) {
                                console.error(error);
                            }
                        });
                        layer.close(index);
                    });
                } else if (obj.event == 'edit') {
                    document.querySelector('#id').value = data.id;
                    document.querySelector('#name').value = data.name;
                    document.querySelector('#email').value = data.email;
                    document.querySelector('#age').value = data.age;
                    document.querySelector('#password').value = '';
                    document.querySelector('#isAdmin_false').checked = !data.isAdmin;
                    document.querySelector('#isAdmin_true').checked = data.isAdmin;
                    dialogType = 'edit';
                    dialogIndex = layer.open({
                        type: 1,
                        title: '编辑',
                        area: ['520px', 'auto'],
                        content: $('#dialog form'),
                    });
                }
            });
        });
    </script>
</body>

</html>